#include "test/test_buffer.h"
#include "net/buffer.h"

TestStdin::TestStdin(net::Poller* poller)
    : poller_(poller), buffer_(new net::Buffer) {
  fd_ = STDIN_FILENO;
  ev_.fd = fd_;
  ev_.arg = this;
  ev_.cb = read_cb;

  CHECK_NOTNULL(poller);
  CHECK(poller_->Add(&ev_, EV_READ));
}

void TestStdin::read_cb(int fd, void* arg, int event) {
  TestStdin* obj = (TestStdin*) arg;

  obj->ReadAndPrint();
}

void TestStdin::ReadAndPrint() {
  static int16 call_cnt = 0;
  buffer_->ReadFd(fd_);

  u_char tmp_buf[4096] = { '\0' };
  ::memcpy(tmp_buf, buffer_->Retrieve(buffer_->ReadableSize()),
           buffer_->ReadableSize());
  LOG(INFO)<< "read fd(" << fd_ << ") size: " << ::strlen((const char*)tmp_buf)
  << "\ndata: " << tmp_buf << "\n";

  if (call_cnt++ >= read_cnt) {
    buffer_->Revert();
  }
}
